const os = require('os')

function getIPAddress() {
  const networkInterfaces = os.networkInterfaces()
  if (!networkInterfaces) {
    return '127.0.0.1'
  }

  for (const name of Object.keys(networkInterfaces)) {
    const interfaces = networkInterfaces[name]
    if (!interfaces) {
      continue
    }

    for (const net of interfaces) {
      // 过滤出IPv4非loopback地址
      if (net && net.family === 'IPv4' && !net.internal) {
        return net.address
      }
    }
  }
  return '127.0.0.1' // 如果没有找到合适的IP，返回localhost
}

module.exports = { getIPAddress }
